package com.jiyun.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.jiyun.pojo.Emp;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtils {
    /**
     * 设置excel下载响应头属性
     */
    private static void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("/+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    public static void exportExcel(HttpServletResponse response, List list,String filename,String sheetname){

        try {
            setExcelRespProp(response,filename);
            EasyExcel.write(response.getOutputStream())
                    // 标题行
                    .head(Emp.class)
                    // excel的类型
                    .excelType(ExcelTypeEnum.XLSX)
                    // sheet的名称
                    .sheet(sheetname)
                    // 数据
                    .doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 导出
    }

}
